package com.pifuke.patient.ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import cn.o.app.adapter.IItemView;
import cn.o.app.adapter.OAdapter;
import cn.o.app.adapter.OItemView;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.FlowLayout;
import cn.o.app.ui.FlowLayout.OnLinesChangeListener;
import cn.o.app.ui.OImageView;
import cn.o.app.util.OUtil;

import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.pifuke.patient.R;
import com.pifuke.patient.SkinApp;
import com.pifuke.patient.SymptomActivity;
import com.pifuke.patient.SymptomActivity.SymptomExtra;
import com.pifuke.patient.SymptomQuestionActivity;
import com.pifuke.patient.SymptomQuestionActivity.SymptomQuestionExtra;
import com.smiier.skin.SearchQuestionActivity;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.SymptomPatientTask;
import com.smiier.skin.net.SymptomPatientTask.SymptomPatientData;
import com.smiier.skin.net.SymptomPatientTask.SymptomPatientItem;
import com.smiier.skin.net.SymptomPatientTask.SymptomPatientRequest;
import com.smiier.skin.net.SymptomPatientTask.SymptomPatientResponse;
import com.smiier.skin.net.SysGetVerTask;
import com.smiier.skin.net.SysGetVerTask.SysGetVerRequest;
import com.smiier.skin.net.SysGetVerTask.SysGetVerResponse;
import com.smiier.skin.net.SysGetVerTask.SysVerItem;
import com.smiier.skin.net.SysGetVerTask.SysVerList;
import com.smiier.skin.ui.BasicFragment;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.utils.Util;

/*
 * 咨询
 * */
public class QuestionCategoryFragment extends BasicFragment {

	protected PullToRefreshListView mListView;

	protected QuestionCategoryAdapter mAdapter;
	View headView;
	// TextView headView;
	protected SparseBooleanArray mExpandPositions = new SparseBooleanArray();
	Drawable mOnePos, mTwoPos, mThreePos, mFourPos;

	public QuestionCategoryFragment(Context context) {
		super(context);
	}

	public QuestionCategoryFragment(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public QuestionCategoryFragment(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		this.setContentView(R.layout.fragment_question_category);

		init();
		this.setNavTitle("咨询");
		back.setVisibility(View.GONE);

		mListView = this.findViewById(R.id.list, PullToRefreshListView.class);

		headView = this.findViewById(R.id.seacher_dd, FrameLayout.class);

		// 设置头部搜索框
		/*
		 * headView = LayoutInflater.from(getContext()).inflate(
		 * R.layout.view_search_button, null);
		 */

		headView.findViewById(R.id.btn_search).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						headView.setVisibility(View.INVISIBLE);
						startActivity(new Intent(getContext(),
								SearchQuestionActivity.class));
					}
				});
		/* mListView.getListView().addHeaderView(headView); */

		mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				loadData();
			}

			@Override
			public void onPullUpToLoadMore(
					PullToRefreshBase<ListView> refreshView) {

			}

		});

		mAdapter = new QuestionCategoryAdapter();
		Resources res = getResources();
		mOnePos = res.getDrawable(R.drawable.ic_face_question);
		mTwoPos = res.getDrawable(R.drawable.ic_question_category);
		mThreePos = res.getDrawable(R.drawable.ic_child_question);
		mFourPos = res.getDrawable(R.drawable.ic_pifu_question);
		mOnePos.setBounds(0, 0, mOnePos.getIntrinsicWidth(),
				mOnePos.getIntrinsicHeight());
		mTwoPos.setBounds(0, 0, mTwoPos.getIntrinsicWidth(),
				mTwoPos.getIntrinsicHeight());
		mThreePos.setBounds(0, 0, mThreePos.getIntrinsicWidth(),
				mThreePos.getIntrinsicHeight());
		mFourPos.setBounds(0, 0, mFourPos.getIntrinsicWidth(),
				mFourPos.getIntrinsicHeight());
		loadData();
	}

	@Override
	public void onResume() {
		super.onResume();
		if (SkinApp.Symptoms == null || SkinApp.Symptoms.size() < 1) {
			SkinApp.Symptoms = new ArrayList<SymptomPatientItem>();
			// requestSymptomData(true);
			String str = CommonUtility.getStringToBean(SkinApp.Symptoms,
					"Symptom_Patient.txt", getContext());
			try {
				SkinApp.Symptoms = JsonUtil.convert(str,
						SymptomPatientResponse.class);
				myHandler.sendEmptyMessage(0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			setData(SkinApp.Symptoms);
		}
		// MobclickAgent.onResume(getContext());
		headView.setVisibility(View.VISIBLE);
	}

	protected void loadData() {
		if (SkinApp.Symptoms == null || SkinApp.Symptoms.size() < 1) {
			SkinApp.Symptoms = new ArrayList<SymptomPatientItem>();
			// requestSymptomData(true);
			String str = CommonUtility.getStringToBean(SkinApp.Symptoms,
					"Symptom_Patient.txt", getContext());
			try {
				SkinApp.Symptoms = JsonUtil.convert(str,
						SymptomPatientResponse.class);
				myHandler.sendEmptyMessage(0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// setData(SkinApp.Symptoms);

			/**
			 * 检查是否存在file文件
			 */

			SkinApp.Symptoms = getSymptomData();
			if (SkinApp.Symptoms == null) {
				requestSymptomData(true);
			} else {
				setData(SkinApp.Symptoms);
			}

			/**
			 * 子线程 查看 updates
			 */

			new Thread(new Runnable() {

				@Override
				public void run() {
					doCheckDataVersion();

				}
			}).start();

		}
	}

	private ArrayList<SymptomPatientItem> getSymptomData() {
		File file = new File(getContext().getCacheDir() + File.separator
				+ "Symptom");
		FileReader fr;
		try {
			fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			StringBuilder sb = new StringBuilder();
			String s;
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}

			/*
			 * GlobalSettings.mHospital = JsonUtil.convert(sb.toString(),
			 * Hospital.class); for (AreaHospital hos :
			 * GlobalSettings.mHospital) { for (SubAreaHospital subhos :
			 * hos.Value) { for (HospitalItem hositem : subhos.Value) {
			 * GlobalSettings.mHospitalItems.add(hositem); } } }
			 */

			ArrayList<SymptomPatientItem> data = null;
			data = JsonUtil.convert(sb.toString(), SymptomPatientData.class);

			return data;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private void doCheckDataVersion() {

		SysGetVerRequest req = new SysGetVerRequest();
		SysGetVerTask task = new SysGetVerTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<SysGetVerTask.SysGetVerRequest, SysGetVerTask.SysGetVerResponse>() {

			@Override
			public void onException(
					INetTask<SysGetVerRequest, SysGetVerResponse> task,
					Exception e) {
			}

			@Override
			public void onComplete(
					INetTask<SysGetVerRequest, SysGetVerResponse> task,
					final SysGetVerResponse response) {
				if (response.ResultCode != 200) {
					return;
				}
				if (response.Res == null) {
					return;
				}
				SysVerList cacheSysVerList = GlobalSettings
						.getSysVerList(getContext());
				new Thread() {
					public void run() {
						for (SysVerItem item : response.Res) {
							if (item.Name.equals("Symptom")) {
								File file = new File(getContext().getCacheDir()
										+ File.separator + "Symptom");
								if (item.Update || !file.exists()) {
									// 更新疾病类型数据
									// cacheHospital(file);
								}
							}
						}
					}

				}.start();
			}
		});
		add(task);

	}

	private void cacheHospital(final File file) {
		try {
			FileOutputStream out = new FileOutputStream(file);
			byte[] b = Util.getHtmlByteArray(GlobalSettings.SERVER_URL
					+ Constant.URL.REQUEST_SYMPTOM_PATIENT_JSON);
			SkinApp.Symptoms = JsonUtil.convert(b.toString(),
					SymptomPatientData.class);

			myHandler.sendEmptyMessage(0);

			out.write(b);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void requestSymptomData(final boolean b) {
		SymptomPatientTask task = new SymptomPatientTask();
		task.addListener(new NetTaskListener<SymptomPatientTask.SymptomPatientRequest, SymptomPatientTask.SymptomPatientResponse>() {

			@Override
			public void onException(
					INetTask<SymptomPatientRequest, SymptomPatientResponse> task,
					Exception e) {
			}

			@Override
			public void onComplete(
					INetTask<SymptomPatientRequest, SymptomPatientResponse> task,
					SymptomPatientResponse response) {

				if (response != null && response.size() > 0) {
					SkinApp.Symptoms = response;
					if (b) {
						setData(response);
					}

				}
			}
		});

		add(task);

	}

	private void setData(ArrayList<SymptomPatientItem> response) {
		mListView.doComplete();
		if (mListView.getListView().getAdapter() == null) {
			mListView.setAdapter(mAdapter);
		}
		mAdapter.setDataProvider(response);
		mAdapter.notifyDataSetChanged();
	}

	static class QuestionCategoryItem {
		public String title;
		public ArrayList<String> symptoms;
	}

	class QuestionCategoryAdapter extends OAdapter<SymptomPatientItem> {

		@Override
		public IItemView<SymptomPatientItem> getItemView() {
			return new QuestionCategoryItemView(getContext());
		}

	}

	int mSize;

	class QuestionCategoryItemView extends OItemView<SymptomPatientItem> {

		protected View mTopArea;
		protected OImageView mCategoryIcon;
		protected TextView mCategoryTitleText;
		protected TextView mCategoryMoreButton;
		protected FlowLayout mCategoryLayout;

		protected int mSymptomPaddingV;
		protected int mSymptomPaddingH;
		protected int mColorBorderBlue;
		protected int mTextSize;
		protected Drawable mArrowDown, mArrowUp;

		public QuestionCategoryItemView(Context context) {
			super(context);

		}

		@Override
		public void onCreate() {
			this.setContentView(R.layout.item_question_category);
			mTopArea = this.findViewById(R.id.top_area, View.class);
			mCategoryIcon = this.findViewById(R.id.ic_category,
					OImageView.class);
			Resources mRes = getResources();
			mCategoryTitleText = this.findViewById(R.id.category_title,
					TextView.class);
			mCategoryMoreButton = this.findViewById(R.id.category_more,
					TextView.class);
			mCategoryLayout = this.findViewById(R.id.category_layout,
					FlowLayout.class);
			mCategoryMoreButton.setVisibility(View.INVISIBLE);
			mColorBorderBlue = mRes.getColor(R.color.border_blue);
			mTextSize = (int) mRes.getDimension(R.dimen.text_size_14);
			mArrowDown = mRes.getDrawable(R.drawable.arrow_down);
			mArrowUp = mRes.getDrawable(R.drawable.arrow_up);
			mArrowDown.setBounds(0, 0, mArrowDown.getIntrinsicWidth(),
					mArrowDown.getIntrinsicHeight());
			mArrowUp.setBounds(0, 0, mArrowUp.getIntrinsicWidth(),
					mArrowUp.getIntrinsicHeight());
			mSymptomPaddingV = (int) OUtil.dp2px(getContext(), 6);
			mSymptomPaddingH = (int) OUtil.dp2px(getContext(), 15);
			mCategoryMoreButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mSize = mAdapter.getDataProvider().size();
					if (mCategoryLayout.getMaxLines() == 1) {
						mCategoryLayout.setMaxLines(-1);
						mCategoryMoreButton.setText("收起");
						mExpandPositions.put(mPosition, true);
						mCategoryMoreButton.setCompoundDrawables(null, null,
								mArrowUp, null);
						if (mPosition == (mSize - 1)) {
							mListView.getListView().setStackFromBottom(true);
						} else {
							mListView.getListView().smoothScrollToPosition(
									mPosition + 1);
						}

						// mListView.getListView().setStackFromBottom(true);

					} else {
						mCategoryLayout.setMaxLines(1);
						mCategoryMoreButton.setText("更多");
						mExpandPositions.put(mPosition, false);
						mCategoryMoreButton.setCompoundDrawables(null, null,
								mArrowDown, null);
						if (mPosition == (mSize - 1)) {
							mListView.getListView().setStackFromBottom(false);
						}

					}
				}
			});

			mCategoryLayout
					.setOnLinesChangeListener(new OnLinesChangeListener() {

						@Override
						public void onChanged(FlowLayout v, int lines) {
							if (v.getMaxLines() == -1) {
								if (lines == 1) {
									mCategoryMoreButton
											.setVisibility(View.INVISIBLE);
									mExpandPositions.put(mPosition, false);
								} else {
									mCategoryMoreButton
											.setVisibility(View.VISIBLE);
									mCategoryMoreButton.setText("隐藏");
									mExpandPositions.put(mPosition, true);
									mCategoryMoreButton.setCompoundDrawables(
											null, null, mArrowUp, null);
								}
							} else {
								if (lines == 1) {
									mCategoryMoreButton
											.setVisibility(View.INVISIBLE);
									mExpandPositions.put(mPosition, false);
								} else {
									mCategoryMoreButton
											.setVisibility(View.VISIBLE);
									mCategoryMoreButton.setText("更多");
									mCategoryMoreButton.setCompoundDrawables(
											null, null, mArrowDown, null);
									mExpandPositions.put(mPosition, false);
								}
							}
						}
					});
		}

		@Override
		public void onResume() {
			mTopArea.setVisibility(mPosition == 0 ? View.VISIBLE : View.GONE);

			mCategoryTitleText.setText(mDataProvider.Type);
			if (mPosition == 0) {
				mCategoryIcon.setImageDrawable(mOnePos);
			} else if (mPosition == 1) {
				mCategoryIcon.setImageDrawable(mTwoPos);
			} else if (mPosition == 2) {
				mCategoryIcon.setImageDrawable(mThreePos);
			} else if (mPosition == 3) {
				mCategoryIcon.setImageDrawable(mFourPos);
			}

			mCategoryLayout.removeAllViews();
			mCategoryLayout.setMeasuredLines(0);

			Resources r = this.getContext().getResources();
			for (int i = 0; i < mDataProvider.Symptoms.size(); i++) {
				if (i >= 20) {
					break;
				}
				Drawable symptomDrawable = r
						.getDrawable(R.drawable.d_filter_btn);

				TextView symptomButton = new TextView(getContext());
				symptomButton.setTag(i);
				symptomButton.setTextColor(mColorBorderBlue);
				// symptomButton.setTextSize(mTextSize);
				symptomButton.setClickable(true);
				symptomButton.setBackgroundDrawable(symptomDrawable);
				symptomButton.setPadding(mSymptomPaddingH, mSymptomPaddingV,
						mSymptomPaddingH, mSymptomPaddingV);
				symptomButton
						.setText(mDataProvider.Symptoms.get(i).Patient_Name);
				final String url = mDataProvider.Symptoms.get(i).Url;
				symptomButton.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						int symptomPos = (Integer) v.getTag();
						if (url != null && !url.trim().equals("")) {
							/**
							 * 科普
							 */
							Intent intent = new Intent(getContext(),
									SymptomActivity.class);
							SymptomExtra extra = new SymptomExtra();
							extra.symptom = mDataProvider.Symptoms
									.get(symptomPos).Patient_Name;
							extra.putTo(intent);
							startActivity(intent);
						} else {
							Intent intent = new Intent(getContext(),
									SymptomQuestionActivity.class);
							SymptomQuestionExtra extra = new SymptomQuestionExtra();
							extra.symptom = mDataProvider.Symptoms
									.get(symptomPos).Patient_Name;
							extra.putTo(intent);
							startActivity(intent);
						}
					}
				});

				if (url != null && !url.trim().equals("")) {
					Drawable popularDrawable = r
							.getDrawable(R.drawable.ic_popular);
					symptomButton.setCompoundDrawablePadding((int) (OUtil
							.dp2px(getContext(), 5)));
					symptomButton.setCompoundDrawablesWithIntrinsicBounds(
							popularDrawable, null, null, null);
				}
				symptomButton.setGravity(Gravity.CENTER_VERTICAL);
				mCategoryLayout.addView(symptomButton);
			}
			if (mCategoryLayout.getLines() <= 1) {
				mCategoryMoreButton.setVisibility(View.GONE);
			}
			boolean expand = mExpandPositions.get(mPosition, false);
			if (expand) {
				mCategoryLayout.setMaxLines(-1);
			} else {
				mCategoryLayout.setMaxLines(1);
			}
		}
	}

	private Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				setData(SkinApp.Symptoms);
				break;

			default:
				break;
			}
		}
	};

	/*
	 * @Override public void onPause() { super.onPause();
	 * MobclickAgent.onPause(getContext()); }
	 */

}
